package io.renren.api;


import cn.hutool.core.collection.CollectionUtil;
import io.renren.core.annotation.LoginUser;
import io.renren.entity.*;
import io.renren.service.*;
import io.renren.utils.ConfigConstant;
import io.renren.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/default")
public class ApiDefaultController {

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private UserDefaultInfoService userDefaultInfoService;

    @Autowired
    private ZanService zanService;

    @Autowired
    private CountService countService;

    @Autowired
    private BookVideoService bookVideoService;

    /**
     * 保存用户身份
     *
     * @return
     */
    @RequestMapping("/saveUserIdentity")
    public R saveUserIdentity(@RequestParam(defaultValue = "0") String identity, @LoginUser WxUser wxUser,
                              HttpSession httpSession) {

        if (identity.trim().equals("0") || identity.trim().equals("1") || identity.trim().equals("2")) {
        } else {
            identity = "0";
        }
        if (!identity.trim().equals(wxUser.getIdentity())) {
            wxUser.setIdentity(identity);
            wxUser.setUpdateTime(new Date());
            wxUserService.update(wxUser);
            //保存后更新session
            httpSession.setAttribute(ConfigConstant.SESSION_USER_KEY, wxUser);
        }

        return R.ok();
    }

    /**
     * 设置默认年级
     *
     * @param gradeId
     * @param wxUser
     * @return
     */
    @RequestMapping("/setDefaultGrade")
    public R setDefaultGrade(@RequestParam Long gradeId, @LoginUser WxUser wxUser) {

        if (wxUser.getGradeId() == null || !gradeId.equals(wxUser.getGradeId())) {
            wxUser.setGradeId(gradeId);
            wxUser.setUpdateTime(new Date());
            wxUserService.update(wxUser);
        }
        return R.ok();
    }

    /**
     * 获取默认的教版
     *
     * @param gradeId
     * @param subjectId
     * @param wxUser
     * @return
     */
    @RequestMapping("/getDefaultVersion")
    public R getDefaultVersion(@RequestParam Long gradeId,
                               @RequestParam Long subjectId,
                               @LoginUser WxUser wxUser) {
        //根据年级科目，获取默认信息
        Map query = new HashMap();
        query.put("gradeId", gradeId);
        query.put("subjectId", subjectId);
        query.put("seasonId",ConfigConstant.DEFAULT_SEASON_ID);
        query.put("userId", wxUser.getId());
        List<UserDefaultInfo> userDefaultInfoList = userDefaultInfoService.queryList(query);
        String defaultVersionId = null;
        if (userDefaultInfoList != null && userDefaultInfoList.size() > 0) {
            defaultVersionId = userDefaultInfoList.get(0).getVersionId() + "";
        }

        return R.ok().put("defaultVersionId", defaultVersionId);
    }

    /**
     * 设置用户默认基本信息
     *
     * @param gradeId
     * @param subjectId
     * @param versionId
     * @param wxUser
     * @return
     */
    @RequestMapping("/setInfo")
    public R setDefaultInfo(@RequestParam Long gradeId,
                            @RequestParam Long subjectId,
                            @RequestParam Long versionId,
                            @LoginUser WxUser wxUser) {

        if (wxUser.getGradeId() == null || !gradeId.equals(wxUser.getGradeId())) {
            wxUser.setGradeId(gradeId);
            wxUserService.update(wxUser);
        }
        //设置默认的科目和教版
        //1. 根据年级科目查询默认信息
        Map query = new HashMap();
        query.put("gradeId", gradeId);
        query.put("subjectId", subjectId);
        query.put("seasonId", ConfigConstant.DEFAULT_SEASON_ID);
        query.put("userId", wxUser.getId());
        List<UserDefaultInfo> userDefaultInfoList = userDefaultInfoService.queryList(query);
        UserDefaultInfo userDefaultInfo ;
        //如果没有则创建
        if (CollectionUtil.isEmpty(userDefaultInfoList)) {
            userDefaultInfo = new UserDefaultInfo();
            userDefaultInfo.setGradeId(gradeId);
            userDefaultInfo.setSubjectId(subjectId);
            userDefaultInfo.setVersionId(versionId);
            userDefaultInfo.setSeasonId(Long.parseLong(ConfigConstant.DEFAULT_SEASON_ID));
            userDefaultInfo.setUserId(wxUser.getId());
            userDefaultInfoService.save(userDefaultInfo);
        } else {
            //否则更新
            userDefaultInfo = userDefaultInfoList.get(0);
            userDefaultInfo.setGradeId(gradeId);
            userDefaultInfo.setSubjectId(subjectId);
            userDefaultInfo.setVersionId(versionId);
            userDefaultInfo.setUpdateTime(new Date());
            userDefaultInfoService.update(userDefaultInfo);
        }

        return R.ok();
    }

    // 获取统计数据
    @RequestMapping("/getCount")
    public R getCount(@RequestParam Long videoId, @LoginUser WxUser wxUser) {

        Boolean isClick = false;

        //1. 获取点赞数量
        Count count = countService.queryObject(videoId);

        //2. 获取用户是否点赞
        Map query = new HashMap<>();
        query.put("videoId", videoId);
        query.put("userId", wxUser.getId());
        List<Zan> zans = zanService.queryList(query);

        if (zans != null && zans.size() > 0 && "1".equals(zans.get(0).getStatus())) {
            isClick = true;
        }

        return R.ok()
                .put("count", count)
                .put("isClick", isClick);
    }

    // 设置点赞信息
    @RequestMapping("/setZan")
    public R setZan(@RequestParam Long videoId, @RequestParam Integer status, @LoginUser WxUser wxUser) {

        BookVideo video = bookVideoService.queryObject(videoId);
        if (video == null) {
            return R.error("该视频不存在,无法点赞");
        }

        //点赞
        zanService.updateZans(wxUser.getId(), videoId, status == 0 ? "0" : "1");

        return R.ok();
    }

    /**
     * 设置视频观看次数
     *
     * @param videoId
     * @return
     */
    @RequestMapping("/setViews")
    public R setView(@RequestParam Long videoId, @LoginUser WxUser wxUser) {

        //查看视频是否有效
        BookVideo video = bookVideoService.queryObject(videoId);
        if (video == null) {
            return R.error("该视频不存在");
        }
        countService.updateViews(videoId);
        return R.ok();
    }

}
